package com.tongjie.hotelbooking.controller.im;

import com.tongjie.hotelbooking.dto.DtoConverters;
import com.tongjie.hotelbooking.dto.MemberConversationDto;
import com.tongjie.hotelbooking.http.BaseResponse;
import com.tongjie.hotelbooking.im.conversation.entiry.MemberConversation;
import com.tongjie.hotelbooking.im.conversation.service.MemberConversationService;
import com.tongjie.hotelbooking.security.SecurityHelper;
import com.tongjie.hotelbooking.security.user.CurrentUserInfo;
import com.tongjie.hotelbooking.user.entity.User;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/im/conversation")
@CrossOrigin
public class ConversationController {

    @Resource
    private MemberConversationService memberConversationService;

    @GetMapping("/current")
    public void currentUserConversation() {
        CurrentUserInfo currentUserInfo = SecurityHelper.getCurrentUserInfo();
    }

    @GetMapping("/memberConversations")
    public BaseResponse<List<MemberConversationDto>> memberConversationList() {
        List<MemberConversation> data = this.memberConversationService.findMemberConversationsByMemberUser(User.builder().id(SecurityHelper.getCurrentUserInfo().getId()).build());
        List<MemberConversationDto> dataList = data.stream().map(input -> MemberConversationDto.builder()
                .id(input.getId())
                .conversationId(input.getConversation().getId())
                .memberUserId(input.getMemberUser().getId())
                .memberConversationName(input.getMemberConversationName())
                .redDot(input.getRedDot())
                .avatar(input.getAvatar())
                .build()).collect(Collectors.toList());
        return BaseResponse.success(dataList);
    }

    @GetMapping("/currentMemberConversation")
    public BaseResponse<MemberConversationDto> memberConversationByTargetUserId(@RequestParam Long targetUserId) {
        MemberConversation memberConversation = this.memberConversationService.getCurrentMemberConversationByUsers(
                User.builder().id(SecurityHelper.getCurrentUserInfo().getId()).build(),
                User.builder().id(targetUserId).build()
        );
        if (memberConversation == null) {
            return BaseResponse.fail("找不到会话");
        }
        return BaseResponse.success(Optional.of(memberConversation).map(DtoConverters::memberConversationToMemberConversationDto).get());
    }


    @GetMapping("/conversation")
    public BaseResponse<Long> getConversationId(@RequestParam Long targetUserId) {
        return null;
    }


}
